//
//  SocketClient.m
//  AppShellTool
//
//  Created by IOS01 on 2022/12/7.
//

#import "SocketClient.h"
#import "IPTool.h"
#import "ShellLuanchTool.h"

@interface SocketClient() <GCDAsyncSocketDelegate>

@property(nonatomic, strong) NSTimer *timer;

@end

@implementation SocketClient

static SocketClient *client;
+ (SocketClient *)shareClient{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        client = [[SocketClient alloc]init];
        client.cSocket = [[GCDAsyncSocket alloc] initWithDelegate:client delegateQueue:dispatch_get_global_queue(0, 0)];
    });
    return client;
}

//- (NSTimer *)timer{
//    if (_timer == nil) {
//        _timer = [[NSTimer alloc] init];
//    }
//    return _timer;
//}


/// 十秒后重连一次
- (void)reconnectAfterTenSecend{
    NSInteger timeInterval = 10;
    
    self.timer = [NSTimer timerWithTimeInterval:timeInterval target:self selector:@selector(connect) userInfo:nil repeats:NO];
    
    NSRunLoop *runloop=[NSRunLoop mainRunLoop];
    [runloop addTimer:self.timer forMode:NSRunLoopCommonModes];
}

- (void)connect{
    [self.cSocket disconnect];
    NSError *err = nil;
    NSString *ip = [IPTool getCurrentLocalIP];
    NSLog(@"local ip is:------%@",ip);
    [self.cSocket connectToHost:ip?ip:@"127.0.0.1" onPort:8888 error:&err];
    if (err) {
        NSLog(@"链接失败:%@",err.description);
    }
}

- (void)sendMsg:(NSString *)msg{
    NSString *sendMsg = [msg stringByAppendingString:@"#"];
    [self.cSocket writeData:[sendMsg dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:1000];
    
}

- (void)disConnect{
    [self.cSocket disconnect];
}

- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port{
    NSLog(@"链接成功：%@---%i",host,port);
    [sock readDataWithTimeout:-1 tag:0];
    [sock performBlock:^{
            [sock enableBackgroundingOnSocket];
        }];
}

- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err{
    NSLog(@"连接失败：%@",err.description);
    if ([ShellLuanchTool shareTool].isShellPush) {
        [self reconnectAfterTenSecend];
    }
}

- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{
    [sock readDataWithTimeout:-1 tag:0];
}

@end
